#include "planeMesh.h"

using namespace sde;

PlaneMesh::PlaneMesh(std::string _type, std::string _name, Object* _object) :
    SceneNode(_type,_name,_object),
    localSceneNode(0),
    entity(0) {
}

void PlaneMesh::run() {
    SceneNode::run();
    
    if (sceneManager && sceneNode) {
        entity = sceneManager->createEntity(object->name,Ogre::SceneManager::PT_PLANE);
        localSceneNode = sceneNode->createChildSceneNode(object->name + std::string("_planeNode"));
        localSceneNode->attachObject(entity);
        
        updateMaterial(object->getVar("material",std::string("Examples/BumpyMetal")));
        object->subscribeSetVar("material",boost::bind(&PlaneMesh::updateMaterial,this,_1));
        
        updateNormal(object->getVar("normal",Vector3::UNIT_Y));
        object->subscribeSetVar("normal",boost::bind(&PlaneMesh::updateNormal,this,_1));
    }
}

void PlaneMesh::updateMaterial(Var val) {
    if (boost::any_cast<std::string>(&val) && entity) {
        std::string material = boost::any_cast<std::string>(val);
        entity->setMaterialName(material);
    }
}

void PlaneMesh::updateNormal(Var val) {
    if (boost::any_cast<Vector3>(&val) && localSceneNode) {
        Vector3 normal = boost::any_cast<Vector3>(val);
        log("normal %s",normal.toString().c_str());
        Quaternion rot = Vector3::UNIT_Z.getRotationTo(normal);
        localSceneNode->setOrientation(GfxServer::QuaternionToOgreQuaternion(rot));
    }
}
